package servlet;

import dao.MessageDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/admin/delete")
public class DeleteMessageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (!"authenticated".equals(session.getAttribute("admin"))) {
            response.sendRedirect(request.getContextPath() + "/adminLogin.jsp");
            return;
        }

        int messageId = Integer.parseInt(request.getParameter("id"));

        try {
            MessageDAO messageDAO = new MessageDAO();
            messageDAO.deleteMessage(messageId);
            response.sendRedirect(request.getContextPath() + "/admin?deleted=true");
        } catch (SQLException e) {
            request.setAttribute("error", "删除留言失败");
            request.getRequestDispatcher("/admin.jsp").forward(request, response);
        }
    }
}